<template>
  <div id="homePage" class="background-image" @click="panelClick" v-loading="loading" element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.3)">
    <el-container>
      <el-header class="shadow-blur lines-blue">
        <div class="cu-list menu-avatar headerTitle">
          <div class="cu-avatar leftTitle">
            <div @click="multiClick" class="text">
              {{ showname }}
            </div>
            <div class="middleTitle" @click="multiClick">
              自助报告打印系统
            </div>
            <div class="cu-item">
              <div class="action text-white">
                <div class="text-white text-right" style="font-size: 18px">
                  <i class="el-icon-date"></i>
                  <span class="margin-left-sm">{{ curDateObj.datetime }}</span>
                  <div class="cuIcon-notice_forbid_fill text-white text-right">
                    <span>{{ curDateObj.AmPm }}</span>
                    <span class="margin-left-sm">{{ curDateObj.time }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="center" v-if="pageIndex === 'first'">
          <div class="leftSon">
            <div class="SonTopBox">
              <el-input id="keyvalueRef" ref="keyvalueRef" style="width: 100%" v-model="keyvalue"
                :placeholder="placeholderText" @keyup.enter="transpatNo(keyvalue)" :disabled="pageIndex === 'second'">
                <template #prepend>
                  <el-button icon='el-icon-bank-card' type="primary" class='idNoButton' @click="idNoClick">读卡</el-button>
                </template>
                <template #suffix>
                  <div class="buttonImg" @click="deleteNumber">
                    <img src="../../../assets/images/ssreport/button.png" alt="" />
                  </div>
                </template>
              </el-input>
            </div>
            <div class="SonButtomBox">
              <div class="imgBox">
                <img src="../../../assets/images/ssreport/hushi.png" alt="" class="no-pointer-event" />
              </div>
            </div>
          </div>
          <div class="rightSon">
            <div class="buttonBox">
              <div class="flex justify-center margin-top" style="height: 100%">
                <div class="light radius" style="position: relative">
                  <el-row :gutter="20" class="padding-lg" style="height: 100%">
                    <el-col class="padding-xs numberCol" :span="8 * item.multiple" v-for="(item, index) in btnList"
                      :key="index">
                      <el-button :disabled="okConfirmCount > 0" ref="buttonKey" :class="item.name"
                        class="numberKey text-xl" type="primary" :style="{ width: item.multiple === 1 ? '90%' : '95%' }"
                        v-if="item.title != ''" @touchend="keyboardClick(item)" @click="keyboardClick(item)">{{ item.title
                        }}
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="pageIndex === 'second'">
          <transition name="el-fade-in-linear">
            <el-card class="box-card" v-if="pageIndex === 'second'">
              <div v-if="tableData.length > 0" class="margin-top-lg" style="height: calc(100%); position: relative">
                <div class="margin-top-lg">
                  <div>
                    <span class="text-bold text-xs text-shadow">姓名：{{ patientInfo.fullName }}</span>
                    <span class="text-bold text-xs margin-left-sm text-shadow">性别：{{
                      patientInfo.sex === '1' ? '男' : patientInfo.sex === '2' ? '女' : '' }}</span>
                    <span class="text-bold text-xs margin-left-sm text-shadow">年龄：{{ patientInfo.age }}</span>
                    <span class="text-bold text-xs margin-left-sm text-shadow">就诊编号：{{ patientInfo.patNo
                    }}</span>
                  </div>
                  <div class="margin-top-lg">
                    <span class="text-xs text-shadow">
                      待打印报告：
                      <span class="text-green">{{
                        tableData.length > 0
                        ? tableData.filter((data) => data.statusValue)
                          .length
                        : 0
                      }}份
                      </span>
                    </span>
                    <span class="text-xs text-shadow margin-left">
                      未出报告：
                      <span class="text-red">{{
                        tableData.length > 0
                        ? tableData.filter((data) => !data.statusValue)
                          .length
                        : 0
                      }}份
                      </span>
                    </span>
                  </div>
                </div>
                <div class="margin-top-xl table">
                  <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName" :show-header="false"
                    height="calc(100% - 75px)">
                    <el-table-column label="序号" width="60" align="center">
                      <template #default="scope">
                        <span :class="scope.row.statusValue === false ? 'warning-row' : ''
                          ">{{ scope.$index + 1 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="scheduleDate" label="日期" width="120" align="left" show-overflow-tooltip>
                      <template #default="scope">
                        <span :class="scope.row.statusValue === false ? 'warning-row' : ''
                          ">{{
    formatDateTimeStr(
      scope.row.scheduleDate,
      'yyyy-MM-dd'
    )
  }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="statusText" label="状态" width="110" align="left">
                      <template #default="scope">
                        <span :class="scope.row.statusValue ? 'text-green' : 'text-red'
                          ">
                          <i :class="scope.row.statusValue
                            ? 'el-icon-circle-check'
                            : 'el-icon-warning-outline'
                            "></i>
                          {{ scope.row.statusText }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="applicationItems" label="报告名称" min-width="110" align="left">
                      <template #default="scope">
                        <span>{{
                          IsEmptyStr(scope.row.applicationItems)
                          ? '检验报告第[' + (scope.$index + 1) + ']份'
                          : scope.row.applicationItems
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="name" label="是否打印" width="50" align="left">
                      <template #default="scope">
                        <i class="el-icon-success text-green" v-if="scope.row.printStatus == 2"></i>
                        <i class="el-icon-loading text-orange" v-if="scope.row.printStatus == 1"></i>
                        <i class="el-icon-remove text-grey" v-if="scope.row.printStatus == 0"></i>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div class="goBack">
                  <el-button type="primary" class="bg-gradual-blue shadow text-shadow text-bold numberKey"
                    style="width: 100%; height: 100%" @click="goBack">
                    <span>返回</span>
                  </el-button>
                </div>
              </div>
              <div v-if="tableData.length <= 0" class="margin-top-lg"
                style="height: calc(100% - 20px); position: relative">
                <div class="margin-top-lg flex justify-center">
                  <span class="margin-top-lg"></span>
                  <span class="text-lg margin-top-lg text-orange text-bold" style="margin-top: 10%">查不到可打印的报告</span>
                </div>
                <div class="goBack">
                  <el-button type="primary" class="bg-gradual-blue shadow text-shadow text-bold"
                    style="width: 100%; height: 100%" @click="goBack">
                    <span>返回</span>
                  </el-button>
                </div>
              </div>
            </el-card>
          </transition>
        </div>
      </el-main>
      <el-footer class="footText">技术支持: 医顺达(山东)信息技术有限公司</el-footer>
    </el-container>
    <transition name="el-fade-in-linear">
      <div class="countDown" @click="printTest" v-if="!includePrint">
        <div class="bg-gradual-orange shadow round text-shadow text-bold text-center" circle
          style="width: 100%; height: 100%">
          <div>
            <span class="text-lg">{{ countDown }}</span>
            <span class="text-xs">s</span>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watch, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { initWebSocket, closeWebSocket } from '@/utils/websocket';
import { ElMessage, ElMessageBox } from 'element-plus';



export default defineComponent({
  name: 'HomePage',
  setup() {
    let { proxy }: any = getCurrentInstance(); // 获取当前实例
    //#region Refs
    let keyvalueRef = ref(null);
    let buttonKey = ref([]);
    let hosname = ref((window as any).hosname ?? 'XXX');
    let placeholderText = ref((window as any).inputText ?? '请输入病历号');
    let loading = ref(false);
    let isLoading = ref(false);
    let drawerIsConfirmClosed = ref(false);
    let pageIndex = ref('first');
    let isManual = ref(false);
    let drawer = ref(false);
    let drawerSize = ref('60%');
    let isPrind = ref(false);
    let includePrint = ref(true);
    let isClickReadCard = ref(false);
    let readCardTime = ref(null);
    let readCardValue = ref('读卡');
    let readCardNum = ref(10);
    let direction = ref('btt');
    let count = ref(0);
    let countDown = ref(5);
    let sleep = ref(5);
    let countTime = ref(null);
    let inputClass = ref('input-top');
    let curDateObj = ref({ datetime: '', time: '', AmPm: '' });
    let options = ref({
      title: 'Current count: 0',
      class: 'modern',
    });
    let carmId = ref('');
    let pattype = ref('');
    let orgId = ref('');
    let isenablewtfilter = ref(false);
    let wts: any = reactive([]);
    let reprint = ref(false);
    let days = ref(-1);
    let showname = ref('');
    let timer = ref(null);
    let keyvalue = ref('');
    let patientInfo = ref({});
    let tableData: any = reactive([]);
    let btnList = ref([
      {
        title: '1',
        name: 'red',
        color: '#e54d42',
        multiple: 1,
        key: '1',
      },
      {
        title: '2',
        name: 'orange',
        color: '#f37b1d',
        multiple: 1,
        key: '2',
      },
      {
        title: '3',
        name: 'yellow',
        color: '#fbbd08',
        multiple: 1,
        key: '3',
      },
      {
        title: '4',
        name: 'olive',
        color: '#8dc63f',
        multiple: 1,
        key: '4',
      },
      {
        title: '5',
        name: 'green',
        color: '#39b54a',
        multiple: 1,
        key: '5',
      },
      {
        title: '6',
        name: 'cyan',
        color: '#1cbbb4',
        multiple: 1,
        key: '6',
      },
      {
        title: '7',
        name: 'blue',
        color: '#0081ff',
        multiple: 1,
        key: '7',
      },
      {
        title: '8',
        name: 'purple',
        color: '#6739b6',
        multiple: 1,
        key: '8',
      },
      {
        title: '9',
        name: 'mauve',
        color: '#9c26b0',
        multiple: 1,
        key: '9',
      },
      {
        title: '0',
        name: 'pink',
        color: '#e03997',
        multiple: 1,
        key: '0',
      },
      {
        title: 'X',
        name: 'brown',
        color: '#a5673f',
        multiple: 1,
        key: 'X',
      },
      {
        title: '清空',
        name: 'black',
        color: '#333333',
        multiple: 1,
        key: 'clear',
      },
      {
        title: '确定',
        name: 'white',
        color: '#ffffff',
        multiple: 2,
        key: 'ok',
      },
    ]);
    const okConfirmCount = ref(0);
    const clickcount = ref(0);
    const lastTime = ref(new Date().getTime());
    const clickTimer = ref(null);
    const waitTime = ref(250);
    //#endregion


    onMounted(() => {
      // toggleFullScreen();
      pageIndex.value = 'first';
      const width = document.documentElement.clientWidth;
      if (width <= 1440) {
        drawerSize.value = '71%';
      } else if (width <= 1024) {
        drawerSize.value = '77%';
      }
      openInputKeyboard();

      let num = (window as any).indexOpenNum;
      if (isNaN(num)) {
        const aref = 'indexOpenNum';
        window[aref] = -1;
        num = (window as any).indexOpenNum;
      }
      if (num && num <= 0) {
        document.removeEventListener('initSystem', () => { });
        document.addEventListener('initSystem', (ev: any) => {
          if (!IsEmpty(ev)) {
            countDown.value = ev.detail.sleep;
            sleep.value = ev.detail.sleep;
            carmId.value = ev.detail.carmid;
            try {
              if (!IsEmpty(ev.detail.pattype)) {
                pattype.value = ev.detail.pattype;
              }
              if (
                ev.detail.isenablewtfilter &&
                ev.detail.wts &&
                ev.detail.wts.length > 0
              ) {
                isenablewtfilter.value = ev.detail.isenablewtfilter;
                wts = ev.detail.wts;
              }
              if (ev.detail.reprint) {
                reprint.value = ev.detail.reprint;
              }
              if (!ev.detail.reprint || ev.detail.reprint === null) {
                reprint.value = false;
              }
              if (!IsEmpty(ev.detail.days) && ev.detail.days > 0) {
                days.value = ev.detail.days;
              }
              if (!IsEmpty(ev.detail.showname)) {
                showname.value = ev.detail.showname;
              }
            } catch (error) {
              //
            }
          }
        });

        document.removeEventListener('readCradFinishNextPrint', () => { });
        document.addEventListener('readCradFinishNextPrint', (ev: any) => {
          console.log('获取到卡号', ev);
          if (!IsEmpty(ev)) {
            loadReportsByMedicalRecNos(ev.detail);
          }
        });
        document.removeEventListener('loadOk', () => { });
        document.addEventListener('loadOk', (ev: any) => {
          //this.$message({ message: '初始化完成', type: "success" });
          openInputKeyboard();
        });
        // 键盘监听事件
        document.addEventListener('KeyDownUp', (ev) => {
          if (pageIndex.value === 'first') {
            keyvalue.value += (ev as any).detail.key;
            proxy.$forceUpdate();
          }
        });
        // 键盘监听结束事件
        document.addEventListener('keyDownUpFinish', (ev) => {
          if (!IsEmpty(keyvalue.value) && pageIndex.value === 'first') {
            confirmInput(keyvalue.value);
          }
        });

        document.removeEventListener('scanFinish', () => { });
        document.addEventListener('scanFinish', (ev: any) => {
          console.log('ev', ev);

          keyvalue.value = ev.detail;
          orgId.value = ev.detail.orgId;
          if (!IsEmpty(keyvalue)) {
            confirmInput(keyvalue);
          }
          okConfirmCount.value = 0;
        });

        document.addEventListener('readCradFinish', (ev) => {
          keyvalue.value = (ev as any).detail.key;
          orgId.value = (ev as any).detail.orgId;
          if (!IsEmpty(keyvalue.value)) {
            confirmInput(keyvalue.value);
          }
          okConfirmCount.value = 0;
        });

        // document.addEventListener('updatePrintStatus', (ev) => {
        //   let para = (ev as any).detail.key;
        //   this.tableData[Number(para)].printStstus = Number((ev as any).detail.status);
        // });
        document.removeEventListener('printFinish', () => { });
        document.addEventListener('printFinish', (ev) => {
          let para = (ev as any).detail.key;
          //this.$alert((ev as any).detail.key);
          proxy.$message({ message: para, type: 'success' });
          showCountDown();
          okConfirmCount.value = 0;
        });
        //转换卡号
        document.removeEventListener('transPatNoFinish', () => { });
        document.addEventListener('transPatNoFinish', (ev) => {
          let para = (ev as any).detail;
          try {
            if (
              para &&
              para.status &&
              (para.status === '1' || para.status === 1)
            ) {
              orgId.value = para.orgId;
              confirmInput(para.key);
            } else {
              //this.$message({ message: para.key, type: "error" });
              pageIndex.value = 'second';
              showCountDown();
              keyvalue.value = '';
            }
            okConfirmCount.value = 0;
          } catch (error) {
            //todo
            okConfirmCount.value = 0;
          }
        });
        //打印失败
        document.removeEventListener('printError', () => { });
        document.addEventListener('printError', (ev) => {
          let para = (ev as any).detail.key;
          proxy.$message({ message: para, type: 'error' });
        });
        document.removeEventListener('updatePrintStatus', () => { });
        document.addEventListener('updatePrintStatus', (ev) => {
          let para = (ev as any).detail.key;
          try {
            tableData[Number(para)].printStatus = Number(
              (ev as any).detail.status
            );
            if (
              Number((ev as any).detail.status) == 2 &&
              (ev as any).detail &&
              (ev as any).detail.carmid
            ) {
              proxy.updateCarmPrintStatus(
                tableData[Number(para)].wlId,
                (ev as any).detail.carmid,
                true
              );
            }
          } catch (error) {
            //todo
          }
          proxy.$forceUpdate();
        });

        (window as any).indexOpenNum = 1;
      } else {
        const aref = 'indexOpenNum';
        window[aref] = 1;
      }

      timer.value = setInterval(() => {
        curDateObj.value.datetime = formatDateTime(new Date(), 'yyyy-MM-dd');
        curDateObj.value.time = formatDateTime(new Date(), 'hh:mm:ss');
        const date = new Date();
        const hours = date.getHours();
        if (hours >= 0 && hours < 12) {
          curDateObj.value.AmPm = '上午';
        } else {
          curDateObj.value.AmPm = '下午';
        }
        openInputKeyboard();
      }, 1000);

      setTimeout(() => {
        openInputKeyboard();
      }, 1000);
    });


    //#region Watchers
    watch(keyvalue, (val, old) => {
      if (isClickReadCard.value && !IsEmpty(val)) {
        clearDisableAboutReadCard();
      }
    });

    watch(tableData, (val, old) => {

      if (!IsEmpty(val) && isPrind.value) {
        let noFinishNum = 0;
        tableData.forEach((element) => {
          if (element.printStstus === 0 || element.printStstus === 1) {
            noFinishNum++;
          }
        });
        if (tableData.length > 0 && noFinishNum === 0) {
          isPrind.value = false;
          showCountDown();
        }
      }
    });
    //#endregion

    //#region Methods
    const toggleFullScreen = () => {
      const elem = document.documentElement;
      if (elem.requestFullscreen) {
        elem.requestFullscreen();
      } else if (elem.requestFullscreen) {
        elem.requestFullscreen();
      } else if (elem.requestFullscreen) {
        elem.requestFullscreen();
      } else if (elem.requestFullscreen) {
        elem.requestFullscreen();
      }
    };

    const formatDateTimeStr = (val, fmt) => {
      return formatDateTime(val, fmt);
    };

    const IsEmptyStr = (val) => {
      return IsEmpty(val);
    };

    const updateCarmPrintStatus = (wlId, carmId, state) => {
      proxy.$http
        .post('/lab/maininfo/updateMainInfoPrintStatus', {
          id: wlId,
          carMachineId: carmId,
          printStatus: state,
        })
        .then((res: any) => { })
        .catch((err) => {
          if ((window as any).winformobj) {
            (window as any).winformobj.recordWebLogs(JSON.stringify(err));
          }
        });
    };

    const tableRowClassName = (data) => {
      if (data.rowIndex % 2 === 0) {
        return 'odd-row';
      }
    };

    const clickReadCard = () => {
      isClickReadCard.value = true;
      readCardValue.value = readCardNum.value + '';
      readCardTime.value = setInterval(() => {
        readCardValue.value = parseInt(readCardValue.value) - 1 + '';
        if (parseInt(readCardValue.value) === 0) {
          clearDisableAboutReadCard();
        }
      }, 1000);
      keyvalue.value = (window as any).winformobj.readCard();
    };

    const clearDisableAboutReadCard = () => {
      clearInterval(readCardTime.value);
      readCardValue.value = '读卡';
      isClickReadCard.value = false;
    };

    const openInputKeyboard = () => {
      inputClass.value = '';
      if (!keyvalueRef.value) {
        setTimeout(() => {
          openInputKeyboard();
        }, 30);
      }
      if (keyvalueRef.value) {
        keyvalueRef.value.focus();
      }
    };

    const drawerClosed = () => {
      if (!drawerIsConfirmClosed.value) {
        keyvalue.value = '';
        isManual.value = true;
        inputClass.value = 'input-top';
      }
    };

    const drawerOpened = () => {
      // ToDo
    };

    const keyboardClick = (item: any) => {
      try {
        switch (item.key) {
          case '0':
          case '1':
          case '2':
          case '3':
          case '4':
          case '5':
          case '6':
          case '7':
          case '8':
          case '9':
          case 'X':
            if (keyvalue.value.length >= 30) {
              return;
            }
            keyvalue.value += item.key;
            break;
          case 'backspace':
            keyvalue.value =
              keyvalue.value.length > 0
                ? keyvalue.value.substr(0, keyvalue.value.length - 1)
                : '';
            break;
          case 'clear':
            keyvalue.value = '';
            break;
          case 'ok':
            okConfirmCount.value++;
            if (IsEmpty(keyvalue.value)) {
              return;
            }
            if (keyvalue.value === '075') {
              if ((window as any).winformobj) {
                (window as any).winformobj.closeApp('我要关闭你');
              }
              return;
            }
            if (okConfirmCount.value > 1) {
              return;
            }
            transpatNo(keyvalue.value);
            break;
          default:
            break;
        }
      } catch (error) {
        //todo
      }
    };

    const idNoClick = () => {
      initWebSocket((item) => {
        const hasName = 'sbkh' in item.data;
        if (hasName) {
          return;
        }

        if (item.code == 0) {
          keyvalue.value = item.data.sfzh;
          transpatNo(keyvalue.value);
        } else {
          ElMessage({ message: item.msg, type: 'warning' });
        }

        closeWebSocket();
      });
    };

    const transpatNo = (keyvalue) => {
      if ((window as any).winformobj) {
        (window as any).winformobj.changePatNo(keyvalue);
      } else {
        okConfirmCount.value = 0;
      }
    };

    const confirmInput = (value: any) => {
      ElMessage({ message: pattype.value, type: 'warning' });
      // 先清除倒计时定时器
      clearCountDown();
      // 清除读卡的禁用
      clearDisableAboutReadCard();
      inputClass.value = '';
      drawerIsConfirmClosed.value = true;
      drawer.value = false;
      loading.value = true;
      let num = 0;
      const loadingTime = setInterval(() => {
        let text =
          document.getElementsByClassName('el-loading-text')[0].innerHTML;
        if (++num > 3) {
          text = '加载中';
          num = 0;
        } else {
          text += '.';
        }
        document.getElementsByClassName('el-loading-text')[0].innerHTML = text;
      }, 400);

      let dataObj = {
        patNos: [value],
        days: days.value,
        pattype: pattype.value,
        orgId: orgId.value,
      } as any;

      try {
        // if (this.pattype && this.pattype.length > 0) {
        //   dataObj['patType'] = [...this.pattype];
        // }
        if (reprint) {
          dataObj['reprint'] = true;
        }
        if (!reprint) {
          dataObj['reprint'] = false;
        }
        if (!IsEmpty(days) && days.value > 0) {
          dataObj['beginDate'] = formatDateTime(
            new Date().valueOf() - days.value * 24 * 60 * 60 * 1000,
            'yyyy-MM-dd'
          );
        }
        if (isenablewtfilter) {
          dataObj['isenablewtfilter'] = true;
          const arList = [];
          wts.forEach(item => {
            console.log('item.Code', item);
            arList.push(item.Code);
          });
          dataObj['wts'] = [...arList];
        }
      } catch (error) {
        // 清除加载动画定时器
        clearInterval(loadingTime);
      }
      tableData.length = 0;
      proxy.$http
        .post('/lab/maininfo/findLabMainInfos', dataObj)
        .then((res: any) => {
          pageIndex.value = 'second';
          isManual.value = false;
          loading.value = false;
          if (res) {
            // 清除加载动画定时器
            clearInterval(loadingTime);
            // 一秒后自动调用打印接口
            const printTime = setTimeout(() => {
              printTest(tableData);
              // 清除定时器
              clearTimeout(printTime);
            }, 1000);
            Object.assign(tableData, res.data.reports ? res.data.reports : [])
            //tableData.push(res.data.reports ? res.data.reports : []);
            // ElMessage({
            //   message: tableData,
            //   type: 'error'
            // });
            Object.assign(patientInfo, res.data);
            // patientInfo.fullName = res.data.patNa;
            // patientInfo.sex = res.data.sex;
            // patientInfo.age = res.data.age;
            // patientInfo.medicalRecordNo = res.data.patNo;
          } else {
            clearInterval(loadingTime);
            tableData.length = 0;
            patientInfo = {} as any;
            pageIndex.value = 'second';
            showCountDown();
          }
        })
        .catch((err) => {
          clearInterval(loadingTime);
          pageIndex.value = 'second';
          showCountDown();
          keyvalue.value = '';
          inputClass.value = 'input-top';
          isManual.value = false;
          loading.value = false;
          tableData.length = 0;
          patientInfo = {} as any;

          //this.$message({ message: "暂无可打印报告", type: "warning" });
        });
    };

    const showCountDown = () => {
      clearCountDown();
      includePrint.value = false;
      countTime.value = setInterval(() => {
        if (--countDown.value === 0) {
          goBack();
        }
      }, 1000);
    };

    const panelClick = () => {
      if (keyvalueRef.value) {
        keyvalueRef.value.focus();
      }
    };

    const clearCountDown = () => {
      clearInterval(countTime.value);
      includePrint.value = true;
      countDown.value = sleep.value;
    };

    const loadReportsByMedicalRecNos = (data) => {
      // 清除读卡的禁用
      clearDisableAboutReadCard();
      inputClass.value = '';
      drawerIsConfirmClosed.value = true;
      drawer.value = false;
      loading.value = true;
      let num = 0;
      const loadingTime = setInterval(() => {
        let text =
          document.getElementsByClassName('el-loading-text')[0].innerHTML;
        if (++num > 3) {
          text = '加载中,请稍后...';
          num = 0;
        } else {
          text += '.';
        }
        document.getElementsByClassName('el-loading-text')[0].innerHTML = text;
      }, 400);
      proxy.$http
        .post('/lab/maininfo/findLabMainInfos', data)
        .then((res: any) => {
          pageIndex.value = 'second';
          isManual.value = false;
          loading.value = false;
          if (res) {
            clearCountDown();
            tableData = Object.assign([], res.reports);
            Object.assign(patientInfo, res);
            // this.patientInfo.fullName = res.fullName;
            // this.patientInfo.sex = res.sex;
            // this.patientInfo.age = res.age;
            // this.patientInfo.medicalRecNo = res.medicalRecNo;
            printTest(tableData);
          } else {
            tableData.length = 0;
            patientInfo = {} as any;
            showCountDown();
          }
          clearInterval(loadingTime);
        })
        .catch((err) => {
          pageIndex.value = 'first';
          keyvalue.value = '';
          inputClass.value = 'input-top';
          isManual.value = false;
          loading.value = false;
          tableData = [] as any[];
          patientInfo = {} as any;
          clearInterval(loadingTime);
          showCountDown();
          proxy.$notify({
            message: '查无报告' + err,
            title: '提示',
            duration: 2500,
          });
        });
    };

    const showWindow = () => {
      if ((window as any).winformobj) {
        (window as any).winformobj.showWindow();
      }
    };

    const printTest = (arrData) => {
      let arr1 = [];
      arrData.forEach((item, index) => {
        if (item.statusValue && item.printStatus == 0) {
          arr1.push({
            key: index,
            ReportName: item.reportObjectCode,
            ReportParameters: [{ Name: 'Id', Value: item.reportId }],
            PdfPrinterSetting: {
              PdfPrinterCopies: 1,
            },
          });
        }
      });

      if (arr1.length <= 0) {
        showCountDown();
        return;
      }

      const paramObj = {
        Header: {
          AccessToken: localStorage.getItem('token'),
        },
        Bodys: arr1,
      };

      if ((window as any).winformobj) {
        (window as any).winformobj.printReports(JSON.stringify(paramObj));
        isPrind.value = true;
      }
    };

    const goBack = () => {
      okConfirmCount.value = 0;
      tableData.value = [];
      keyvalue.value = '';
      isManual.value = false;
      pageIndex.value = 'first';
      inputClass.value = 'input-top';
      drawer.value = false;
      drawerIsConfirmClosed.value = false;
      timer.value = null;
      timer.value = setInterval(() => {
        curDateObj.value.datetime = formatDateTime(new Date(), 'yyyy-MM-dd');
        curDateObj.value.time = formatDateTime(new Date(), 'hh:mm:ss');
        const date = new Date();
        const hours = date.getHours();
        if (hours >= 0 && hours < 12) {
          curDateObj.value.AmPm = '上午';
        } else {
          curDateObj.value.AmPm = '下午';
        }
      }, 1000);
      clearCountDown();
    };

    const closeApp = () => {
      if ((window as any).winformobj) {
        (window as any).winformobj.closeApp('我要关闭你');
      }
    };

    const multiClick = (event) => {
      const currentTime = new Date().getTime();
      clickcount.value =
        currentTime - lastTime.value < waitTime.value ? clickcount.value + 1 : 1;
      lastTime.value = new Date().getTime();
      clearTimeout(clickTimer.value);
      clickTimer.value = setTimeout(() => {
        clearTimeout(clickTimer.value);
        if (clickcount.value > 4) {
          if ((window as any).winformobj) {
            (window as any).winformobj.showDevTool();
          }
          // router.push('/syset');
          clickcount.value = 0;
          lastTime.value = new Date().getTime();
          clearTimeout(clickTimer.value);
          clickTimer.value = null;
          waitTime.value = 250;
        }
      }, waitTime.value + 10);
    };

    const deleteNumber = () => {
      keyvalue.value = keyvalue.value.slice(0, -1);
    };
    //#endregion

    //#region Lifecycle Hooks


    onBeforeUnmount(() => {
      if (timer.value) {
        clearInterval(timer.value);
      }
      if (countTime.value) {
        clearInterval(countTime.value);
      }
      if (readCardTime.value) {
        clearInterval(readCardTime.value);
      }
      if (clickTimer.value) {
        clearTimeout(clickTimer.value);
      }
    });
    //#endregion

    return {
      keyvalueRef,
      buttonKey,
      hosname,
      placeholderText,
      loading,
      isLoading,
      drawerIsConfirmClosed,
      pageIndex,
      isManual,
      drawer,
      drawerSize,
      isPrind,
      includePrint,
      isClickReadCard,
      readCardTime,
      readCardValue,
      readCardNum,
      direction,
      count,
      countDown,
      sleep,
      countTime,
      inputClass,
      curDateObj,
      options,
      carmId,
      pattype,
      orgId,
      isenablewtfilter,
      wts,
      reprint,
      days,
      showname,
      timer,
      keyvalue,
      patientInfo,
      tableData,
      btnList,
      okConfirmCount,
      clickcount,
      lastTime,
      clickTimer,
      waitTime,
      formatDateTimeStr,
      IsEmptyStr,
      updateCarmPrintStatus,
      tableRowClassName,
      clickReadCard,
      clearDisableAboutReadCard,
      openInputKeyboard,
      drawerClosed,
      drawerOpened,
      keyboardClick,
      idNoClick,
      transpatNo,
      confirmInput,
      showCountDown,
      panelClick,
      clearCountDown,
      loadReportsByMedicalRecNos,
      showWindow,
      printTest,
      goBack,
      closeApp,
      multiClick,
      deleteNumber,
    };
  },
});
</script>

<style lang="scss" scoped>
@font-face {
  font-family: "CustomFont";
  src: url("../../../assets/images/ssreport/方正正粗黑_GBK.ttf");
}

#homePage {
  width: 100%;
  height: 100%;
  // height: 100vh;
  position: relative;

  .text {
    font-family: "CustomFont", Arial, sans-serif;
  }

  .el-container {
    height: 100%;
  }

  .el-header {
    padding-top: 45px;
    text-align: center;
    min-height: 150px;

    // .headerTitle {
    //   height: 100%;
    // }
    .cu-list.menu-avatar>.cu-item>.cu-avatar {
      height: 100%;
      width: 100% !important;
      text-align: left;
    }

    .leftTitle {
      display: flex;
      font-size: 3rem;
      color: #fff;
      font-weight: 500;
      margin-left: 10px;
      margin-right: 10px;
    }

    .middleTitle {
      flex-grow: 1;
      text-align: center;
      color: #fff;
      font-weight: 500;
      font-size: 3.5rem;
      font-family: "CustomFont", Arial, sans-serif;
    }
  }

  .el-main {
    color: #333;

    // height: calc(100vh - 160px);
    padding: 0 70px;
    position: relative;
    box-sizing: border-box;

    .center {
      display: flex;
      position: relative;
      width: 100%;
      height: 98%;
      background-color: #f1f1f1;
      border-radius: 30px;
      text-align: center;
      box-sizing: border-box;

      .leftSon {
        width: 60%;
        height: 100%;
        box-sizing: border-box;

        .SonTopBox {
          width: 100%;
          height: 20%;
          padding: 40px 0 0 40px;
          box-sizing: border-box;

          ::v-deep .el-input__suffix {
            width: 4em;
            height: 3em;
            top: 50%;
            transform: translateY(-50%);
            right: 1em;
          }

          .buttonImg {
            height: 60%;
            width: 90%;
            margin-top: 20%;
            display: contents;

            img {
              width: 100%;
              height: 100%;
            }
          }

          ::v-deep .el-input-group__prepend {
            border-top-left-radius: 25px;
            border-bottom-left-radius: 25px;
            color: white;
            background: linear-gradient(to bottom, #025943, #27d3a7);
            text-align: center;
            font-size: 30px;
          }

          .idNoButton {
            height: 40%;
            width: 140%;
            font-size: 22px;
            border-radius: 10px;
          }
        }

        .SonButtomBox {
          position: relative;
          width: 100%;
          height: 80%;

          .imgTextBox {
            position: absolute;
            top: 20%;
            left: 30%;
            font-size: 2em;
            color: #0875fc;
            font-weight: 400;
          }

          .imgBox {
            position: absolute;
            top: 0%;
            bottom: 0%;
            height: 100%;

            img {
              width: 100%;
              height: 100%;
            }
          }
        }
      }

      .rightSon {
        width: 40%;
        height: 100%;
        box-sizing: border-box;
        padding: 20px 40px;

        .text-xl {
          font-size: 4em;
        }

        .black {
          font-size: 2.2em;
        }

        .padding-xs {
          // padding: 5px !important;
        }
      }

      .buttonBox {
        height: 97%;
        width: 100%;
        background-color: #fff;
        border-radius: 30px;

        .numberCol {
          height: 20%;

          // margin-bottom: 30px;
          .numberKey {
            height: 100% !important;
            border-radius: 20px !important;
            background: linear-gradient(to bottom, #045efa, #0988fd);
            padding: 0;
            width: 100% !important;
            border: 0;
          }
        }

        .el-col-16 {
          width: 100%;

          .numberKey {
            background: linear-gradient(to bottom, #06916d, #2ad8ac);
          }
        }
      }
    }

    ::v-deep .el-input {
      // display: block;
      width: 100%;
      // margin-top: 80px;
      transition: margin-top 0.6s;
      transition-delay: 0.3s;

      .el-input__inner {
        // text-align: center;
        font-size: 3em;
        border: 0;
        // font-weight: 800;
        height: 10vh;
        // line-height: 3.2em;
        user-select: none !important;
        // box-shadow: 0 2px 3px rgb(0 0 0 / 15%) inset,
        //   0 0 10px rgb(44 135 219 / 30%);
        color: rgb(64, 158, 255);
        // border-radius: 0.7em;
        border-top-right-radius: 0.7em;
        border-bottom-right-radius: 0.7em;
        // text-align: center;
      }
    }

    .input-top {
      margin-top: 19%;
    }

    ::v-deep .read-card {
      font-size: 1.5em;
      border-radius: 0.7em;
      height: 3.2em;
      line-height: 3.2em;
      width: 6em;
      padding: 0;
      margin-left: 16px;
    }

    ::v-deep .el-card {
      width: 100%;
      margin: 0 auto;
      margin-top: 80px;
      height: calc(100vh - 60px - 40px - 80px - 70px - 80px);
      box-sizing: border-box;
      position: relative;

      .el-card__body {
        height: 100%;
        box-sizing: border-box;
      }

      .content {
        line-height: 2em;
      }

      .table {
        height: calc(100%);
      }

      .el-table {
        .odd-row {
          background-color: #ecf5ff;
        }

        .even-row {
          background-color: #f0f9eb;
        }
      }

      .goBack {
        position: absolute;
        //width: 80px;
        // height: 80px;
        // top: 0.5em;
        top: -10px;
        left: 0.5em;
      }
    }
  }

  .el-footer {
    color: #fff;
    text-align: center;
    height: 60px;
    line-height: 60px;
    letter-spacing: 0.2em;
    font-size: 1em;
    z-index: 1;
  }

  ::v-deep .el-drawer {
    background: rgba($color: #000, $alpha: 0.3);

    .el-icon-close:before {
      color: #fff;
      font-size: 2em;
    }

    .el-drawer__body {
      .el-row {
        width: 95%;
        margin: 0 auto !important;
        padding-bottom: 45px;

        .el-button {
          margin-top: 25px;
          box-shadow: 0 2px 3px #24619e;
        }
      }
    }
  }

  .countDown {
    position: absolute;
    width: 80px;
    height: 80px;
    line-height: 80px;
    top: 88px;
    right: 2.5em;
  }

  .footText {
    text-align: right;
    font-size: 21px;
    padding-right: 85px;
  }

  .box-card {
    width: 65%;
  }

  @media screen and (max-width: 1440px) {
    .cu-item {
      height: 45px;
      width: 200px;
    }

    .el-header {
      padding-top: 45px;

      .action i,
      span {
        font-size: 0.8em;
      }

      .leftTitle {
        font-size: 2.5rem;
      }

      .middleTitle {
        font-size: 3rem;
      }
    }

    .el-main {

      // padding: 10px 20px;
      ::v-deep .el-input {
        // margin-top: 40px;
        transition: margin-top 0.5s;
        transition-delay: 0.2s;

        .el-input__inner {
          font-size: 35px;
          height: 10vh;
          // line-height: 90px;
          // box-shadow: 0 1px 3px rgb(0 0 0 / 15%) inset,
          //   0 0 10px rgb(44 135 219 / 30%);
          border-radius: 0.6em;
        }
      }

      .input-top {
        // margin-top: 19%;
      }

      ::v-deep .read-card {
        font-size: 1.3em;
        border-radius: 0.6em;
        height: 3em;
        line-height: 3em;
      }

      ::v-deep .el-card {
        margin-top: 40px;
        // height: calc(100vh - 60px - 20px - 40px - 55px - 40px - 40px);
        padding: 5px 0px;

        .margin-top-lg {
          margin-top: 12px;
        }

        .content {
          line-height: 2em;
        }

        span {
          font-size: 1.2em;
        }

        .el-button {
          font-size: 1.3em !important;
        }

        .table {
          height: calc(100%);
        }

        .el-table {

          td,
          th {
            padding: 8px 0;
          }

          span {
            font-size: 1em;
          }
        }

        .goBack {
          // width: 75px;
          // height: 75px;
          left: 0;
          top: -10px;

          .el-button {
            font-size: 1em;
          }
        }
      }
    }

    .el-footer {
      height: 40px !important;
      line-height: 40px;
      font-size: 0.8em;
    }

    ::v-deep .el-drawer {
      .el-icon-close:before {
        font-size: 1.7em;
      }

      .el-drawer__body {
        .el-row {
          padding-bottom: 25px;

          .el-button {
            font-size: 1.7em;
            margin-top: 15px;
            box-shadow: 0 1px 2px #24619e;
          }
        }
      }
    }

    .countDown {
      width: 70px;
      height: 70px;
      line-height: 70px;
      top: 60px;

      span {
        font-size: 24px;
      }
    }
  }

  @media screen and (max-width: 1024px) {
    .cu-item {
      height: 36px;
    }

    .el-header {

      .action i,
      span {
        font-size: 0.5em;
      }
    }

    .el-main {
      ::v-deep .el-input {

        // margin-top: 20px;
        .el-input__inner {
          font-size: 25px;
          height: 70px;
          line-height: 70px;
          border-radius: 0.4em;
          margin-top: 0;
        }
      }

      .input-top {
        // margin-top: 19%;
      }

      ::v-deep .read-card {
        font-size: 1.2em;
        border-radius: 0.4em;
        height: 2.5em;
        line-height: 2.5em;
        margin-left: 10px;
      }

      ::v-deep .el-card {
        margin-top: 20px;

        // height: calc(100vh - 60px - 20px - 20px - 42px - 20px - 30px - 100px);
        .el-card__body {
          padding: 0;
        }

        .content {
          line-height: 1.5em;
        }

        span {
          font-size: 1em;
        }

        .el-button {
          font-size: 3em !important;
        }

        .el-table {

          td,
          th {
            padding: 4px 0;
          }

          span {
            font-size: 0.9em;
          }
        }

        .goBack {
          // width: 58px;
          // height: 58px;
          top: -10px;

          .el-button {
            font-size: 1em;
          }
        }
      }
    }

    .el-footer {
      height: 30px !important;
      line-height: 30px;
      font-size: 1em;
    }

    ::v-deep .el-drawer {
      .el-icon-close:before {
        font-size: 1.5em;
      }

      .el-drawer__body {
        .el-row {
          padding-bottom: 20px;

          .el-button {
            margin-top: 10px;
            font-size: 1.5em;
            padding: 10px 20px;
          }
        }
      }
    }

    .countDown {
      width: 58px;
      height: 58px;
      line-height: 58px;
      top: 55px;

      span {
        font-size: 16px;
      }
    }
  }

  @media screen and (max-width: 800px) {}

  /* 自定义滚动条样式 */
  ::v-deep.el-table__body-wrapper::-webkit-scrollbar {
    width: 18px;
    /* 滚动条宽度 */
    background-color: #f5f5f5;
    /* 背景颜色 */
  }

  ::v-deep.el-table__body-wrapper::-webkit-scrollbar-track {
    background-color: rgba($color: #000000, $alpha: 0);
    /* 滚动条轨道背景颜色 */
  }

  ::v-deep.el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #888;
    /* 滚动条滑块颜色 */
    border-radius: 6px;
    /* 滚动条滑块圆角 */
  }

  ::v-deep.el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
    background-color: #555;
    /* 滚动条滑块悬停颜色 */
  }


  // 新增背景样式
  &.background-image {
    background-image: url('@/assets/images/ssreport/bj.jpg'); // 图片路径
    background-size: cover; // 覆盖整个区域
    background-position: center; // 居中显示
    background-repeat: no-repeat; // 不重复
    background-attachment: fixed; // 固定背景

    // 可选：添加半透明遮罩确保内容可读性
    // position: relative;
    // &::before {
    //   content: '';
    //   position: absolute;
    //   top: 0;
    //   left: 0;
    //   right: 0;
    //   bottom: 0;
    //   background: rgba(255, 255, 255, 0.85); // 白色85%透明度
    //   z-index: 0;
    // }

    // 确保内容在遮罩上方
    >* {
      position: relative;
      z-index: 1;
    }
  }

}
</style>